import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import Home from '@/views/Home'
import store from '@/store/index.js'

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  // history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      component: Home,
      meta: { isKeepAlive: true }
    },
    {
      path: '/list',
      component: () => import(/* webpackChunkName: "list" */ '@/views/List.vue'),
      meta: { isKeepAlive: true }
    },
    {
      path: '/cart',
      meta: { needLogin: true },
      component: () => import(/* webpackChunkName: "cart" */ '@/views/Cart.vue')
    },
    {
      path: '/my',
      meta: { needLogin: true },
      component: () => import(/* webpackChunkName: "my" */ '@/views/My.vue')
    },
    {
      path: '/search',
      component: () => import(/* webpackChunkName: "search" */ '@/views/Search'),
      children: [
        {
          path: '',
          component: () => import(/* webpackChunkName: "search_index" */ '@/views/Search/SearchIndex.vue')
        },
        {
          path: 'list',
          component: () => import(/* webpackChunkName: "search_list" */ '@/views/Search/SearchList.vue')
        }
      ]
    },
    {
      path: '/detail',
      component: () => import(/* webpackChunkName: "detail" */ '@/views/Detail.vue'),
      meta: { isKeepAlive: true }
    },
    {
      path: '/login',
      component: () => import(/* webpackChunkName: "login" */ '@/views/login/Login.vue')
    },
    {
      path: '/pwdLogin',
      component: () => import(/* webpackChunkName: "pwdLogin" */ '@/views/login/PwdLogin.vue')
    },
    {
      path: '/register',
      component: () => import(/* webpackChunkName: "register" */ '@/views/login/Register.vue')
    },
    {
      path: '/address',
      meta: { needLogin: true },
      children: [
        {
          path: '',
          component: () => import(/* webpackChunkName: "address" */ '@/views/address/AddressIndex.vue'),
        },
        {
          path: 'editAdd',
          component: () => import(/* webpackChunkName: "address_add_edit" */ '@/views/address/AddressAddEdit.vue')
        }
      ]
    },
    {
      path: '/checkout',
      meta: { needLogin: true },
      component: () => import(/* webpackChunkName: "checkout" */ '@/views/Checkout.vue')
    },
    {
      path: '/order',
      meta: { needLogin: true },
      component: () => import(/* webpackChunkName: "order" */ '@/views/Order.vue')
    },
    {
      path: '/pay',
      meta: { needLogin: true },
      component: () => import(/* webpackChunkName: "pay" */ '@/views/Pay.vue')
    }
  ]
})

router.beforeEach((to) => {
  if (to.meta.needLogin && !store.state.user) {
    return '/login'
  } else {
    return true
  }
})

export default router